package com.mengma.ec.service.impl.portal;

import com.mengma.ec.commons.ServerResponse;
import com.mengma.ec.dao.CategoryMapper;
import com.mengma.ec.entity.Category;
import com.mengma.ec.service.portal.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: xixi
 * @Date: 2018/9/18 09:38
 * @Description:
 */
@Service("iCategoryService")
public class CategoryServiceImpl implements ICategoryService {


    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public ServerResponse<List<Category>> getChildrenParallelCategory(Integer categoryId) {

        List<Category> list = categoryMapper.getChildrenParallelCategory(categoryId);

        if (list == null) {
            return ServerResponse.createByErrorMessage("错误");
        }
        return ServerResponse.createBySuccess(list);
    }

    @Override
    public ServerResponse get_deep_catagory(Integer categoryId) {
        List<Integer> list = new ArrayList<>();

        recusionFindAllChildren(categoryId, list);
        return ServerResponse.createBySuccess(list);


    }


    @Override
    public ServerResponse add_catagory(Integer categoryId, String categoryName) {
        Category category=new Category();
        category.setName(categoryName);
        category.setParentId(categoryId);
        int  count= categoryMapper.insertSelective(category);
        if(count>0){
            return ServerResponse.createBySuccessMessage("新增品类成功");
        }
        return ServerResponse.createByErrorMessage("服务器错误，新增品类失败");
      }

    @Override
    public ServerResponse set_category_name(Integer categoryId, String categoryName) {
        Category category=new Category();
        category.setId(categoryId);
        category.setName(categoryName);
        int RowCount= categoryMapper.updateByPrimaryKeySelective(category);
        if(RowCount>0){
            return ServerResponse.createBySuccessMessage("更新品类名字成功");
        }
        return ServerResponse.createByErrorMessage("服务器错误，更新品类字失败");
    }


    public List<Category> recusionFindAllChildren(Integer categoryId, List<Integer> list) {
        List<Category> list_children = categoryMapper.getChildrenParallelCategory(categoryId);

        // 结束条件
        if (list_children.size() == 0) {
            return null;
        }

        for (Category category : list_children) {
            list.add(category.getId());
            // 开始递归
            recusionFindAllChildren(category.getId(), list);

        }
        return list_children;
    }
}
